import NetInfo, {
  NetInfoState,
  NetInfoSubscription
} from '@react-native-community/netinfo';

class Net {
  private handler: NetInfoSubscription | undefined;

  private changeRes: NetInfoState | undefined;

  private handleFirstConnectivityChange = (res: NetInfoState): void => {
    this.changeRes = res;
  };

  public start = (): void => {
    NetInfo.configure({
      reachabilityUrl: 'https://www.baidu.com',
      reachabilityTest: async response => response.status === 204,
      reachabilityLongTimeout: 60 * 1000, // 60s
      reachabilityShortTimeout: 5 * 1000, // 5s
      reachabilityRequestTimeout: 15 * 1000 // 15s
    });
    NetInfo.fetch().then((res): void => {
      this.changeRes = res;
    });
    this.handler = NetInfo.addEventListener((state: NetInfoState): void =>
      this.handleFirstConnectivityChange(state)
    );
  };

  public stop = (): void => {
    if (this.handler) {
      this.handler();
    }
  };

  public getNetType = (): string => {
    if (!this.changeRes) {
      return 'unknown';
    }
    if (typeof this.changeRes === 'string') {
      return this.changeRes;
    }

    if (this.changeRes.type !== 'cellular') return this.changeRes.type;

    return this.changeRes.details.cellularGeneration || 'unknown';
  };
}

export default new Net();
